/**
 * 离线下载
 */
//查看资源
var publicUtils = require('script/localStorageManagers.js');
var DownloadUtil = require('scripts/Core/DownLoadUtil.js');
var mobileFrame=require('scripts/Core/MobileFrame.js');
var downloadUtils = require('scripts/Core/DownLoadUtil.js');
(function($) {
	mui.init({
		swipeBack: true //启用右滑关闭功能
	});
	$.plusReady(function() {
		initDown();
		
		//切换到已下载
	    mui(document).on('tap', '#downloadedBtn', initDownloaded);
	    //切换到下载中
	    mui(document).on('tap', '#downloadingBtn', initDownloading);
	    //删除下载项
	    if('Android'==plus.os.name)mui('.mui-content').on('longtap', '.mui-slider-handle', deleteDownloadAndroid);
	   if('iOS'==plus.os.name) {mui('.mui-content').on('tap', '.mui-btn-red', deleteDownloadAndroid);}
	});
	
	
	
})(mui);
function initDown(){
	initDownloaded();
	initDownloading();
}
//初始话下载中div 
function initDownloading() {
	
	var curTasks = DownloadUtil.getRequestUrlCachePool();
	//mui.toast(curTasks.length);
	//console.log(curTasks);
	var conCurTasks = DownloadUtil.getConcurrentDownloadTask();
	//mui.toast("当前下载任务数量:"+conCurTasks);
	var downloadingEle = document.getElementById('downloading');
	downloadingEle.innerHTML = '';
	var ifcontent = false;
	//var sessionManagerItem=DownloadUtil.getSessionManagerItem();
	var sessionManagerItem = publicUtils.getDownloadResourceSession();
	var pos = 0;
	if (sessionManagerItem != null) pos = sessionManagerItem.length;
	for (var i = 0; i < pos; i++) {
		var item = sessionManagerItem[i];
		if (DownloadUtil.isDownload(item.path)) continue;
		//key=decodeURI(key);
		//key=key.substring(key.lastIndexOf('_')+1,key.length);
		var restitle = item.title;
		if (restitle != null && restitle.length > 10) restitle = restitle.substring(0, 13) + '...';
		//var info=item.courseName+'-'+item.catalogName+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+'['+item.resCatName+']'+restitle;
		//var liInfo="<li class='mui-table-view-cell'><div class='mui-slider-right mui-disabled'><a class='mui-btn mui-btn-red'>删除</a></div><div class='mui-slider-handle'>"+info+"</div></li>";
		downloadingEle.innerHTML = downloadingEle.innerHTML + buildDownloadingLi(item);
		ifcontent = true;
	}
	if (!ifcontent) {
		downloadingEle.innerHTML = "<li class='mui-table-view-cell' style='text-align:center;'>没有正在下载的资源.</li>";
	} else {
		initDownloadingStatus();
	}
};

function initDownloadingStatus() {
	plus.downloader.enumerate(function(tasks) {
		
		var taskmap={};
		for (var i = 0; i < tasks.length; i++) {
			var task = tasks[i];
			var url=task.url;
			url=url.substring(0,url.indexOf("?"));
			
			taskmap[url]=url;
			//task.resume();
			//mui.toast(task.downloadedSize);
			taskListener(task);
		}
		//alert("当前下载任务数量:"+tasks.length);
		//设置下载标记
		var progressEles = document.getElementsByClassName('progress');
		for (var j = 0; j < progressEles.length; j++) {
			var proEle = progressEles[j];
		   if (!taskmap[proEle.getAttribute('url')]){
		   	var str = '<div><span class="p1">0M</span><span class="p2">/0M</span><span class="p3">下载失败,删除后重试</span></div><div class="ping" style="width:0%"></div>';
		    proEle.innerHTML = str;
		   }
		}
	});
};
//任务监听
function taskListener(task) {
	task.addEventListener("statechanged", function(task, status) {
		var downSize = task.downloadedSize / (1024 * 1024);
		downSize = Math.round(downSize * 100) / 100;
		var totalSize = task.totalSize / (1024 * 1024);
		totalSize = Math.round(totalSize * 100) / 100;
		var baifen = Math.round((downSize / totalSize) * 100);
		var progressEles = document.getElementsByClassName('progress');
		for (var j = 0; j < progressEles.length; j++) {
			var proEle = progressEles[j];
			if (task.url.indexOf(proEle.getAttribute('url')) < 0) continue;
			switch (task.state) {
				case 1: // 开始
					var str = '<div><span class="p1">' + downSize + 'M</span><span class="p2">/' + totalSize + 'M</span><span class="p3">准备下载</span></div><div class="ping" style="width:' + baifen + '%"></div>';
					proEle.innerHTML = str
					break;
				case 2: // 已连接到服务器
					var str = '<div><span class="p1">' + downSize + 'M</span><span class="p2">/' + totalSize + 'M</span><span class="p3">准备下载</span></div><div class="ping" style="width:' + baifen + '%"></div>';
					proEle.innerHTML = str
					break;
				case 3:

					var str = '<div><span class="p1">' + downSize + 'M</span><span class="p2">/' + totalSize + 'M</span><span class="p3">下载中</span></div><div class="ping" style="width:' + baifen + '%"></div>';
					proEle.innerHTML = str;
					break;
				case 4: // 下载完成
					var str = '<div><span class="p1">' + totalSize + 'M</span><span class="p2">/' + totalSize + 'M</span><span class="p3">下载完成</span></div><div class="ping" style="width:100%"></div>';
					proEle.innerHTML = str;
					setTimeout(function() {
						//document.getElementById('downloading').removeChild(proEle.parentElement.parentElement);
					}, 2000);
					break;
			}
		}
	});
}
//初始化已下载
function initDownloaded() {

	var downloadedEle = document.getElementById('downloaded');
	downloadedEle.innerHTML = '';
	var ifcontent = false;
	//var sessionManagerItem=DownloadUtil.getSessionManagerItem();
	var sessionManagerItem = publicUtils.getDownloadResourceSession();
	var pos = 0;
	if (sessionManagerItem != null) pos = sessionManagerItem.length;
	for (var i = 0; i < pos; i++) {
		var item = sessionManagerItem[i];
		if (!DownloadUtil.isDownload(item.path)) continue;
		//key=decodeURI(key);
		//key=key.substring(key.lastIndexOf('_')+1,key.length);
		var restitle = item.title;
		if (restitle != null && restitle.length > 10) restitle = restitle.substring(0, 13) + '...';
		//var info=item.courseName+'-'+item.catalogName+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+'['+item.resCatName+']'+restitle;
		//var liInfo="<li class='mui-table-view-cell'><div class='mui-slider-right mui-disabled'><a class='mui-btn mui-btn-red'>删除</a></div><div class='mui-slider-handle'>"+info+"</div></li>";
		downloadedEle.innerHTML = downloadedEle.innerHTML + buildDownloadedLi(item);
		ifcontent = true;
	}
	review_resource();
	if (!ifcontent)
		downloadedEle.innerHTML = "<li class='mui-table-view-cell' style='text-align:center;'>没有已下载的资源.</li>";

}
//预览资源
function review_resource () {
	//其他应用打开
    mui('#downloaded').on('tap','#downloaded li',function(){
    	var respath=this.getAttribute("respath");
    	respath=downloadUtils.getLocalAbsoluteUrl2(respath);//打开文件需要相对路径
    	console.log(respath);
    	var suffix=respath.substring(respath.lastIndexOf('.')+1,respath.length);
    	if(respath.indexOf('http:')>=0){
    	 //mui.toast('请先下载到本地');
    	plus.runtime.openURL(respath, {}, function ( e ) {
                  plus.nativeUI.alert( "无法打开'"+suffix+"'格式的文件,请安装相关应用." );
         } );
        }else{
         plus.runtime.openFile(respath, {}, function ( e ) {
                  plus.nativeUI.alert( "无法打开'"+suffix+"'格式的文件,请安装相关应用。" );
         } );	
        }
    });
}
//删除下载
function deleteDownloadIOS() {
	var elem = this;
	var li = elem.parentNode.parentNode;
	mui.confirm('确认删除该条记录？', '', null, function(e) {
		if (e.index == 0) {
			var key = li.getAttribute('key');
			li.parentNode.removeChild(li);
			publicUtils.removeDownloadResourceSessionItem(key);
		} else {
			setTimeout(function() {
				mui.swipeoutClose(li);
			}, 0);
		}
	});
};
//删除下载
function deleteDownloadAndroid() {
	var elem = this;
	var li = elem.parentNode;
	if('iOS'==plus.os.name)li=li.parentNode;
	mui.confirm('确认删除该条记录？', '下载', null, function(e) {
		if (e.index == 0) {
			var key = li.getAttribute('key');
			li.parentNode.removeChild(li);
			publicUtils.removeDownloadResourceSessionItem(key);
		} else {
			setTimeout(function() {
				mui.swipeoutClose(li);
			}, 0);
		}
	});
};
/**
 * 构建已下载列表
 * @param {Object} catname
 * @param {Object} catalogname
 * @param {Object} resname
 */
function buildDownloadedLi(item) {
	var restitle = item.title;
	var coursename=item.courseName;
	var catalogname=item.catalogName;
    var resImg='../images/down_default.png';
    if(item.resCatName!='视频')
	 	resImg='../images/down_default1.jpg';
    if(mobileFrame.IsNetWorkCanUse()&&item.resImg!=null&&item.resImg.length>0)resImg=item.resImg;
	var catClass = getCatClass(item.resCatName);
	if (coursename != null && coursename.length > 10) coursename = coursename.substring(0, 10) + '...';
	if (catalogname != null && catalogname.length > 10) catalogname = catalogname.substring(0, 10) + '...';
	if (restitle != null && restitle.length > 10) restitle = restitle.substring(0, 10) + '...';
	var delstr='';
	if('iOS'==plus.os.name)delstr='<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>';
	var li = '<li class="mui-table-view-cell" key="'+item.key+'" respath="'+item.path+'">'+delstr+'<div class="mui-slider-handle ed">';
	li += '<img src="'+resImg+'" class="resimg"/><div><span class="type '+catClass+'">' + item.resCatName + '</span><span>' + restitle + '</span>';
	li += '<p><img src="../images/icon62.png" />' + catalogname + '</p><p><img src="../images/icon62.png" />' + coursename + '</p></div></div></li>';
	return li;
};
/**
 * 构建下载中列表
 * @param {Object} catname
 * @param {Object} catalogname
 * @param {Object} resname
 */
function buildDownloadingLi(item) {
	 var resImg='../images/down_default.png';
	 if(item.resCatName!='视频')
	 	resImg='../images/down_default1.jpg';
	 
	 
    if(item.resImg!=null&&item.resImg.length>0)resImg=item.resImg;
	var restitle = item.title;
	var coursename=item.courseName;
	var catalogname=item.catalogName;
	if (coursename != null && coursename.length > 10) coursename = coursename.substring(0, 10) + '...';
	if (catalogname != null && catalogname.length > 10) catalogname = catalogname.substring(0, 10) + '...';
	if (restitle != null && restitle.length > 10) restitle = restitle.substring(0, 10) + '...';
    var resSize = item.resSize / (1024 * 1024);
	resSize = Math.round(resSize * 100) / 100;
	var catClass = getCatClass(item.resCatName);
	var delstr='';
	if('iOS'==plus.os.name)delstr='<div class="mui-slider-right mui-disabled"><a class="mui-btn mui-btn-red">删除</a></div>';
	var li = '<li class="mui-table-view-cell"  key="'+item.key+'">'+delstr;
	li += '<div class="mui-slider-handle ing" url="' + item.path + '"><img src="'+resImg+'" class="resimg"/><div  class="dinfo"><span class="type '+catClass+'">' + item.resCatName + '</span><span>' + restitle + '</span>';
	li += '<p><img src="../images/icon62.png" />' + catalogname + '</p><p><img src="../images/icon62.png" />' + coursename + '</p></div>';
	li += '<div class="progress"  url="' + item.path + '">';
	li += '<span class="p1">0M</span><span class="p2">/'+resSize+'M</span><span class="p3">等待缓存</span>';
	li += '<div class="ping"></div>';
	li += '</div>';
	li += '</div></li>';
	return li;
};

function getCatClass(preName) {
	var preClass = 'xt';
	switch (preName) {
		case "视频":
			preClass = 'sp';
			break;
		case "讲义":
			preClass = 'jy';
			break;
		case "习题":
			preClass = 'xt';
			break;
		case "教案":
			preClass = 'jy';
			break;
		case "随堂检测":
			preClass = 'stjc';
			break;
		default:
			preClass = 'xt';

	}
	return preClass;
}